<template>
    <el-input v-model="currentVal" v-bind="$attrs" @blur="handleBlur" />
</template>

<script setup>
import { ref, watch } from 'vue';

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
    modelValue: {
        type: [Number, String],
        default: ''
    },
    max: {
        type: [Number, String],
        default: null
    },
    min: {
        type: [Number, String],
        default: null
    }
});

let currentVal = ref('');
watch(
    () => props.modelValue,
    newVal => {
        currentVal.value = ['', null, undefined].includes(newVal) ? '' : newVal + '';
    },
    { immediate: true, deep: true }
);

// const handleInput = val => {
//     console.log(val);
//     currentVal.value =
//         val
//             .replace(/\D*(\d*)(\.?)(\d{0,2})\d*/, '$1$2$3')
//             .replace(/^0+(\d)/, '$1')
//             .replace(/^\./, '0.')
//             .match(/^\d*(\.?\d{0,2})/g)[0] || '';
//     console.log('currentVal.value', currentVal.value);
//     if (['', null, undefined].includes(currentVal.value)) {
//         emit('update:modelValue', null);
//     } else if (props.max && currentVal.value / 1 > props.max / 1) {
//         currentVal.value = props.max / 1;
//         emit('update:modelValue', props.max / 1);
//     } else if (props.min && currentVal.value / 1 < props.min / 1) {
//         currentVal.value = props.min / 1;
//         emit('update:modelValue', props.min / 1);
//     } else {
//         emit('update:modelValue', currentVal.value / 1);
//     }
// };
const handleBlur = val => {
    let currentValue =
        currentVal.value
            .replace(/\D*(\d*)(\.?)(\d{0,2})\d*/, '$1$2$3')
            .replace(/^0+(\d)/, '$1')
            .replace(/^\./, '0.')
            .match(/^\d*(\.?\d{0,2})/g)[0] || '';
    if (['', null, undefined].includes(currentValue)) {
        currentVal.value = null;
        emit('update:modelValue', null);
    } else if (props.max && currentValue / 1 > props.max / 1) {
        currentVal.value = props.max / 1;
        emit('update:modelValue', props.max / 1);
    } else if (props.min && currentValue / 1 < props.min / 1) {
        currentVal.value = props.min / 1;
        emit('update:modelValue', props.min / 1);
    } else {
        currentVal.value = currentValue / 1;
        emit('update:modelValue', currentValue / 1);
    }
};
</script>

<style lang="scss" scoped></style>
